package com.lzh.farmersshop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzh.farmersshop.entity.*;
import com.lzh.farmersshop.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 后台管理跳转地址
 *
 * @author ShiChaojie
 * @date 2024/1/4 15:44
 */
@Slf4j
@Controller
@RequestMapping("mall")
public class ToMallController {

    //商品分类
    @Resource
    private TypeService typeService;
    //轮播图
    @Resource
    private BannerService bannerService;
    //商品
    @Resource
    private GoodsService goodsService;
    //评价
    @Resource
    private EvaluationService evaluationService;
    //商品图
    @Resource
    private GoodsimgService goodsimgService;
    //订单
    @Resource
    private OrderService orderService;
    //购物车
    @Resource
    private ShoppcartService shoppcartService;
    //用户收货地址
    @Resource
    private UseradressService useradressService;
    //订单详情
    @Resource
    private OrderdetailsService orderdetailsService;

    /**
     * 跳转到前台主页
     *
     * @return
     */
    @RequestMapping("index")
    public ModelAndView tIndex(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("mall/index");
        //查询所有商品分类
        mv.addObject("types", typeService.list());
        //查询轮播图前五条数据
        mv.addObject("banners", bannerService.list(new QueryWrapper<Banner>().last("order by id limit 5")));
        //查询出随机三个分类
        List<Type> list = typeService.list(new QueryWrapper<Type>().last("ORDER BY RAND() limit 3"));
        mv.addObject("randomTypes", list);
        for (int i = 0, size = list.size(); i < size; i++) {
            //根据分类id查询这个分类下的8个随机商品信息
            mv.addObject("goods" + i, goodsService.list(new QueryWrapper<Goods>().eq("typeid", list.get(i).getId()).eq("state", 1).last("ORDER BY RAND() limit 8")));
        }
        return this.commentMethodNoUserInfo(request, mv);
    }

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @RequestMapping("login")
    public ModelAndView toLogin() {
        return new ModelAndView("mall/login");
    }

    /**
     * 跳转到个人信息页面
     *
     * @return
     */
    @RequestMapping("userSetting")
    public ModelAndView toUserSetting(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("mall/userSetting");
        return this.commentMethod(request, mv);
    }

    /**
     * 必须有用户信息的方法
     *
     * @return
     */
    private ModelAndView commentMethod(HttpServletRequest request, ModelAndView mv) {
        if (request.getSession().getAttribute("userinfo") == null) {
            //如果为空说明用户没有登录，必须登录后之后才能看购物车
            mv.addObject("userinfo", new Userinfo());
            return new ModelAndView("redirect:/mall/login");
        } else {
            mv.addObject("userinfo", request.getSession().getAttribute("userinfo"));
        }
        Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
        Date birthday = userinfo.getBirthday();
        if (birthday == null) {
            mv.addObject("birthday", "");
        } else {
            // 转换为 LocalDateTime 类型
            LocalDateTime localDateTime = new java.sql.Timestamp(
                    birthday.getTime()).toLocalDateTime();

            // 创建 DateTimeFormatter 对象并设定转换格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            // 格式化日期
            String formattedDate = localDateTime.format(formatter);
            mv.addObject("birthday", formattedDate);
        }
        return mv;
    }

    /**
     * 可以没有用户信息的方法
     *
     * @return
     */
    private ModelAndView commentMethodNoUserInfo(HttpServletRequest request, ModelAndView mv) {
        //获取用户信息
        if (request.getSession().getAttribute("userinfo") != null) {
            mv.addObject("userinfo", request.getSession().getAttribute("userinfo"));
            Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
            Date birthday = userinfo.getBirthday();
            if (birthday == null) {
                mv.addObject("birthday", "");
            } else {
                // 转换为 LocalDateTime 类型
                LocalDateTime localDateTime = new java.sql.Timestamp(
                        birthday.getTime()).toLocalDateTime();

                // 创建 DateTimeFormatter 对象并设定转换格式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                // 格式化日期
                String formattedDate = localDateTime.format(formatter);
                mv.addObject("birthday", formattedDate);
            }
        } else {
            mv.addObject("userinfo", new Userinfo());
        }
        return mv;
    }

    /**
     * 跳转到验证密码页面
     */
    @RequestMapping("userUpdatePwd")
    public ModelAndView toUserUpdatePwd(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("mall/userUpdatePwd");
        return this.commentMethod(request, mv);
    }

    /**
     * 跳转到修改密码页面
     */
    @RequestMapping("userUpdatePwd2")
    public ModelAndView toUserUpdatePwd2(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("mall/userUpdatePwd2");
        return this.commentMethod(request, mv);
    }

    /**
     * 跳转到修改密码完成页面
     */
    @RequestMapping("userUpdatePwd3")
    public ModelAndView toUserUpdatePwd3(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("mall/userUpdatePwd3");
        ModelAndView modelAndView = this.commentMethod(request, mv);
        modelAndView.addObject("userinfo", new Userinfo());
        request.getSession().removeAttribute("userinfo");
        return modelAndView;
    }

    /**
     * 跳转到收货地址页面
     */
    @RequestMapping("userAddress")
    public ModelAndView toUserAddress(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("mall/userAddress");
        if (request.getSession().getAttribute("userinfo") == null) {
            //如果为空说明用户没有登录，必须登录后之后才能看购物车
            mv.addObject("userinfo", new Userinfo());
            return new ModelAndView("redirect:/mall/login");
        }
        Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
        //根据用户id查询用户的收货地址信息
        List<Useradress> adressList = useradressService.list(new QueryWrapper<Useradress>().eq("userid", userinfo.getId()));
        mv.addObject("adressList", adressList);
        return this.commentMethod(request, mv);
    }

    /**
     * 跳转到编辑收货地址页面
     */
    @RequestMapping("userAddressEdit")
    public ModelAndView toUserAddressEdit(HttpServletRequest request, Integer id) {
        ModelAndView mv = new ModelAndView("mall/userAddressEdit");
        mv.addObject("useradress", useradressService.getById(id));
        return this.commentMethod(request, mv);
    }


    /**
     * 跳转到商品详情页面
     *
     * @return
     */
    @RequestMapping("goodsDetail")
    public ModelAndView toGoodsDetail(HttpServletRequest request, Integer id) {
        ModelAndView mv = new ModelAndView("mall/goodsDetail");
        //根据商品id查询商品信息
        Goods goods = goodsService.getById(id);
        mv.addObject("goods", goods);
        //查询该分类下的8个商品
        mv.addObject("goodsList", goodsService.list(new QueryWrapper<Goods>().eq("typeid", goods.getTypeid()).eq("state", 1).last("ORDER BY RAND() limit 8")));
        //查询该商品的评价
        List<Evaluation> evaluationList = evaluationService.findAllByGoodsid(goods.getId());
        mv.addObject("evaluationList", evaluationList);
        mv.addObject("evaluationListSize", evaluationList.size());
        //查询该商品的图片
        mv.addObject("goodsimgList", goodsimgService.list(new QueryWrapper<Goodsimg>().eq("goodsid", goods.getId()).orderByAsc("`index`")));
        //查询出该分类的名称
        mv.addObject("type", typeService.getById(goods.getTypeid()));
        //查询该商品的累计销量
        Long salesVolume = orderService.getSalesVolumeByGoodsId(id);
        mv.addObject("salesVolume", salesVolume);
        return this.commentMethodNoUserInfo(request, mv);
    }

    /**
     * 跳转到分类详情页面
     *
     * @return
     */
    @RequestMapping("typeDetail")
    public ModelAndView toTypeDetail(HttpServletRequest request, Integer id) {
        ModelAndView mv = new ModelAndView("mall/typeDetail");
        //根据分类id查询分类信息
        Type type = typeService.getById(id);
        mv.addObject("type", type);
        //查询该分类下的所有商品
        mv.addObject("goodsList", goodsService.list(new QueryWrapper<Goods>().eq("typeid", type.getId()).eq("state", 1)));
        //获取用户信息
        return this.commentMethodNoUserInfo(request, mv);
    }

    /**
     * 跳转到搜索详情页面
     *
     * @return
     */
    @RequestMapping("searchDetail")
    public ModelAndView toSearchDetail(HttpServletRequest request, String searchText) {
        ModelAndView mv = new ModelAndView("mall/searchDetail");
        //把searchText进行简单的分词
        List<String> keywords = new ArrayList<>();
        for (int len = searchText.length(); len > 0; len--) {
            for (int i = 0; i + len <= searchText.length(); i++) {
                String sub = searchText.substring(i, i + len);
                keywords.add(sub);
            }
        }
        //根据每一个词进行模糊搜索
        List<Goods> goodsList = goodsService.selectDistinctByTitleLike(keywords);
        mv.addObject("goodsList", goodsList);
        mv.addObject("searchText", searchText);
        //获取用户信息
        return this.commentMethodNoUserInfo(request, mv);
    }

    /**
     * 跳转到我的订单页面
     *
     * @return
     */
    @RequestMapping("userOrder")
    public ModelAndView toUserOrder(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("mall/userOrder");
        if (request.getSession().getAttribute("userinfo") == null) {
            //如果为空说明用户没有登录，必须登录后之后才能看购物车
            mv.addObject("userinfo", new Userinfo());
            return new ModelAndView("redirect:/mall/login");
        }

        //获取用户信息
        Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
        //根据用户信息查询用户的所有订单
        List<Order> orderList = orderService.list(new QueryWrapper<Order>().eq("userid", userinfo.getId()).orderByAsc("id"));
        //判断用户有没有订单，如果没有直接返回
        if (orderList.isEmpty()) {
            return mv;
        }
        //获取所有的订单号封装成一个List<Long>
        List<Long> orderNums = new ArrayList<>();
        for (Order order : orderList) {
            Date time = order.getTime();
            // 转换为 LocalDateTime 类型
            LocalDateTime localDateTime = new java.sql.Timestamp(
                    time.getTime()).toLocalDateTime();

            // 创建 DateTimeFormatter 对象并设定转换格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            order.setTimeString(localDateTime.format(formatter));
            orderNums.add(order.getOrderid());
        }
        //创建一个HashMap，键为订单id，值为订单对象：
        Map<Long, Order> orderMap = new HashMap<>();
        for (Order order : orderList) {
            orderMap.put(order.getOrderid(), order);
        }

        //根据所有订单号查询订单详情
        List<Orderdetails> orderdetailsList = orderdetailsService.findAllByOrdernums(orderNums);
        //高效遍历订单，从订单详情中获取自己的订单详情，根据订单id和订单详情里的id
        for (Orderdetails details : orderdetailsList) {
            Long orderid = details.getOrdernum();
            // 从orderMap获取订单号为orderid的实体
            Order correspondingOrder = orderMap.get(orderid);
            if (correspondingOrder != null) {
                // 若存在对应订单，将详情添加到该订单的children中
                if (correspondingOrder.getChildren() == null) {
                    correspondingOrder.setChildren(new ArrayList<>());
                }
                correspondingOrder.getChildren().add(details);
            }
        }
        mv.addObject("orderList", orderList);
        //获取用户信息
        return this.commentMethod(request, mv);
    }

    /**
     * 跳转到我的购物车页面
     *
     * @return
     */
    @RequestMapping("cart")
    public ModelAndView toCart(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("mall/userCart");
        //获取用户信息
        if (request.getSession().getAttribute("userinfo") == null) {
            //如果为空说明用户没有登录，必须登录后之后才能看购物车
            mv.addObject("userinfo", new Userinfo());
            return new ModelAndView("redirect:/mall/login");
        } else {
            mv.addObject("userinfo", request.getSession().getAttribute("userinfo"));
        }
        Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
        //根据用户id查询该用户的购物车信息
        List<Map<String, Object>> list = shoppcartService.findAllCartByUserid(userinfo.getId());
        mv.addObject("shoppcartList", list);
        return this.commentMethod(request, mv);
    }

    //跳转到提交订单页面
    @RequestMapping("userCartPay")
    public ModelAndView toUserCartPay(HttpServletRequest request, Integer id) {

        ModelAndView mv = new ModelAndView("mall/userCartPay");
        if (request.getSession().getAttribute("userinfo") == null) {
            //如果为空说明用户没有登录，必须登录后之后才能看购物车
            mv.addObject("userinfo", new Userinfo());
            return new ModelAndView("redirect:/mall/login");
        }
        //根据id查询订单
        Order order = orderService.getById(id);
        Date time = order.getTime();
        // 转换为 LocalDateTime 类型
        LocalDateTime localDateTime = new java.sql.Timestamp(
                time.getTime()).toLocalDateTime();

        // 创建 DateTimeFormatter 对象并设定转换格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化日期
        String formattedDate = localDateTime.format(formatter);
        mv.addObject("orderTime", formattedDate);
        mv.addObject("order", order);
        //根据订单号查询订单详情
        List<Map<String, Object>> orderdetailList = orderdetailsService.findAllByOrdernum(order.getOrderid());
        mv.addObject("orderdetailList", orderdetailList);
        //根据用户id查询用户的收货地址
        List<Useradress> useradressList = useradressService.list(new QueryWrapper<Useradress>().eq("userid", order.getUserid()));
        mv.addObject("useradressList", useradressList);
        return this.commentMethod(request, mv);
    }

    /**
     * 跳转到评价页面
     */
    @RequestMapping("userComment")
    public ModelAndView toUserComment(HttpServletRequest request, Integer id) {
        ModelAndView mv = new ModelAndView("mall/userComment");
        if (request.getSession().getAttribute("userinfo") == null) {
            //如果为空说明用户没有登录，必须登录后之后才能看购物车
            mv.addObject("userinfo", new Userinfo());
            return new ModelAndView("redirect:/mall/login");
        }
        //根据id查询订单
        Order order = orderService.getById(id);
        Date time = order.getTime();
        // 转换为 LocalDateTime 类型
        LocalDateTime localDateTime = new java.sql.Timestamp(
                time.getTime()).toLocalDateTime();

        // 创建 DateTimeFormatter 对象并设定转换格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化日期
        String formattedDate = localDateTime.format(formatter);
        mv.addObject("orderTime", formattedDate);
        mv.addObject("order", order);
        //根据订单号查询订单详情
        List<Map<String, Object>> orderdetailList = orderdetailsService.findAllByOrdernum(order.getOrderid());
        mv.addObject("orderdetailList", orderdetailList);
        return this.commentMethod(request, mv);
    }

    /**
     * 退出
     */
    @RequestMapping("logout")
    public ModelAndView logout(HttpServletRequest request) {
        request.getSession().removeAttribute("userinfo");
        return new ModelAndView("redirect:/mall/index");
    }


}
